package com.doge.calcalbum.utils

import java.io.File
import java.io.InputStream
import java.io.OutputStream

object FileUtils {
    fun cacheDir(child: String): File {
        return File(
            appContext.cacheDir, child
        ).also { if (!it.exists()) it.mkdirs() }
    }

    fun filesDir(child: String): File {
        return File(
            appContext.filesDir, child
        ).also { if (!it.exists()) it.mkdirs() }
    }

    fun copy(inputStream: InputStream?, outputStream: OutputStream?) {
        if (inputStream == null) return
        if (outputStream == null) return
        try {
            var read: Int
            val bytes = ByteArray(1024)
            while (inputStream.read(bytes).also { read = it } != -1) {
                outputStream.write(bytes, 0, read)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            closeQuietly(inputStream)
            closeQuietly(outputStream)
        }
    }

    fun size(byteCount: Int?) = size(byteCount?.toLong())
    private fun size(byteCount: Long?): String {
        if (byteCount == null) return ""
        if (byteCount < 0) return ""
        if (byteCount < 1024) return "${byteCount}B"
        if (byteCount < 1048576) return "${byteCount / 1024}KB"
        return "${byteCount / 1048576f}MB"
    }


}